var express = require("express");
var router = express.Router();
const db = require("../db/index.js");
const { v4: uuidv4 } = require('uuid');
// 用这个包来生成 Token 字符串
const jwt = require("jsonwebtoken");
// 导入配置文件
const config = require("../config");
// 查询驾照列表 分页
router.get("/licenseList", function (req, res, next) {
  console.log(req.query);
  // 获取参数   当前页码   当前每页数据量
  // 获取参数   当前页码   当前每页数据量
  let pageNumber = req.query.pageNumber;
  // let pageSize = parseInt(req.body.pageSize)
  let pagesize = req.query.pagesize - 0;
  // 求得sql语句中的参数
  console.log(pageNumber, pagesize);
  //  if(!pageNumber) pageNumber=1
  //  if(!pagesize) pagesize=6
  console.log(pageNumber, pagesize);
  let start = (pageNumber - 1) * pagesize;
  // sql语句
  let sql = "select * from license limit ?, ?";
  let sqlParam = [start, pagesize];
  let sqlCount = "select count(*) from license";

  var count = 0;
  // 执行查询
  db.query(sqlCount, null, (err, result) => {
    // 得到总记录数
    count = result[0]["count(*)"];
  });

  db.query(sql, sqlParam, (err, result) => {
    if (err) {
      res.send({
        code: 0,
        message: err.message,
        ok: true,
      });
    } else {
      res.send({
        code: 200,
        message: "请求成功",
        ok: true,
        totalCount: count,
        data: result,
      });
    }
  });
});

// 驾照模糊查询
router.post('/search',function(req,res,next){
  let type  = req.body.type
  const sql =  `SELECT * FROM license where type like '%${type}%' `
  db.query(sql,function(err,results){
    if(err) {return res.send({code:0,message:err.message})} 
    
    res.send({code:200,message:'查询成功!',data:results})
  })
})
//  添加驾照类型
router.post("/addLicense", function (req, res, next) {
  let info = req.body;
  let token = req.headers.token;
  jwt.verify(token, config.jwtSecretKey, function (err, result) {
    // console.log(result);
    if (result.role !== "admin") {
      res.send({ code: 0, message: "您的权限不够" });
    } else {
      const sql = `select *from license where type=?`;
      db.query(sql, info.type, function (err, results) {
        if (err) res.send({ code: 0, message: err.message });
        if (results.length > 0)
          res.send({ code: 0, message: "该用户已经注册" });
        const sql1 = `insert into license set ?`;
        let ID = uuidv4()
        ID = ID.replace(/-/g, '')
        db.query(
          sql1,
          { id:ID,
            type: info.type,
            car: info.car,
            price: info.price,
            img: info.img,
          },
          function (err, data) {
            if (err) res.send({ code: 0, message: err.message });
            res.send({ code: 200, message: "添加成功！" });
          }
        );
      });
    }
  });
});
//删除驾照信息
router.post("/deleteLicense", function (req, res) {
  console.log(req.query);
  let token = req.headers.token;
  let id = req.query.id;
  jwt.verify(token, config.jwtSecretKey, function (err, data) {
    if (data.role !== "admin") {
      res.send({ code: 0, message: "您的权限不够" });
    } else {
      const sql = "delete from license where id=?";
      db.query(sql, id, function (err, result) {
        if (err) res.send({ code: 0, message: err.message });
        res.send({ code: 200, message: "删除成功！" });
      });
    }
  });
});
// 查看详情信息
router.get("/getLicenseInfo", function (req, res) {
  console.log(req.query);
  let id = req.query.id;
  const sql = `select * from license where id=?`;
  db.query(sql, id, function (err, results) {
    if (err) res.send({ code: 0, message: err.message });
    res.send({ code: 200, message: "查询成功", data: results[0] });
  });
});

// 报名
router.post("/application", function (req, res) {
  
  let info = req.body;
  const sql1 = `select * from application where nickname=?`;
    db.query(sql1, info.nickname, function (err, results) {
      if (results.length > 0) {
        return res.send({
          code: 0,
          message: "你已经报过名了，请不要重复报名！",
        });
      } else {
        const sql = `insert into application set ?`;
        let ID = uuidv4()
      ID = ID.replace(/-/g, '')
        db.query(
          sql,
          {
            id:ID,
            nickname: info.nickname,
            type: info.type,
            status: "待审核",
            money: "未支付",
            photo:info.photo
          },
          function (err, result) {
            if (err) res.send({ code: 0, message: err.message });
            res.send({ code: 200, message: "报名成功！" });
          }
        );
      }
    });
});

module.exports = router;
